package com.winit.employeeDataExtract;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.DateCodec;
import com.winit.common.SignGenerator;
import com.winit.employeInfo.model.Dept;
import com.winit.employeInfo.model.Duty;
import com.winit.employeInfo.model.Employee;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 通过https请求获取佩琪数据接口
 */
public class EmployeeDataExtractor {

    private static Logger log = LoggerFactory.getLogger(EmployeeDataExtractor.class);

    public static CookieStore cookieStore = new BasicCookieStore();
    public static CloseableHttpClient httpCilent = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    private static String scheme;
    private static String host;
    private static String path;
    private static String timeOffSet;
    private static Integer language;
    static {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
//            properties.load(ClassLoader.getSystemResourceAsStream("application.properties"));
            scheme = properties.getProperty("data.employee.scheme");
            host = properties.getProperty("data.employee.host");
            path = properties.getProperty("data.employee.path");
            timeOffSet = properties.getProperty("data.employee.timeOffSet");
            language = Integer.valueOf(properties.getProperty("data.employee.language"));
            ParserConfig.getGlobalInstance().setAsmEnable(false);
            ParserConfig.getGlobalInstance().putDeserializer(Date.class, new ObjectDeserializer() {
                @Override
                public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName){
                    try {
                        JSONLexer lexer = parser.getLexer();
                        String str  = lexer.stringVal();
                        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date  date =  dateFormat.parse(str);
                        T t = (T)date;
                        lexer.nextToken();
                        return t;
                    } catch (Exception e) {
                        return  DateCodec.instance.deserialze(parser, type, fieldName);
                    }

                }

                @Override
                public int getFastMatchToken() {
                    return DateCodec.instance.getFastMatchToken();
                }
            });
        } catch (Exception e) {
            log.error("EmployeeDataExtractor  初始化",e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }



    public static List<Duty> extractDuty() throws URISyntaxException, Exception {
        String data = extractData("duty", null, null);
        List<Duty> duties = JSONObject.parseObject(data, new TypeReference<List<Duty>>(){});
        return duties;
    }

    public static List<Duty> extractDuty(String timeOffSet, Integer language) throws URISyntaxException, Exception {
        String data = extractData("duty", timeOffSet, language);
        List<Duty> duties = JSONObject.parseObject(data, new TypeReference<List<Duty>>(){});
        return duties;
    }

    public static List<Dept> extractDept() throws URISyntaxException, Exception {
        String data = extractData("dept", null, null);
        List<Dept> depts = JSONObject.parseObject(data, new TypeReference<List<Dept>>(){});
        return depts;
    }

    public static List<Dept> extractDept(String timeOffSet, Integer language) throws URISyntaxException, Exception {
        String data = extractData("dept", timeOffSet, language);
        List<Dept> depts = JSONObject.parseObject(data, new TypeReference<List<Dept>>(){});
        return depts;
    }
    public static List<Employee> extractEmployee() throws URISyntaxException, Exception {
        String data = extractData("emp", null, null);
        List<Employee> employees = JSONObject.parseObject(data, new TypeReference<List<Employee>>(){});
        return employees;
    }

    public static List<Employee> extractEmployee(String timeOffSet, Integer language) throws URISyntaxException, Exception {
        String data = extractData("emp", timeOffSet, language);
        List<Employee> employees = JSONObject.parseObject(data, new TypeReference<List<Employee>>(){});
        return employees;
    }

    private static String extractData(String type, String timeOffSetUsed, Integer languageUsed) throws URISyntaxException, Exception {
        timeOffSetUsed = null == timeOffSetUsed ? timeOffSet : timeOffSetUsed;
        languageUsed = null == languageUsed ? language : languageUsed;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
                .setConnectionRequestTimeout(50000) // 设置请求超时时间
                .setSocketTimeout(50000).setRedirectsEnabled(true)// 默认允许自动重定向
                .build();
        URI uri = new URIBuilder()
                .setScheme(scheme)
                .setHost(host)
                .setPath(path)
                .setParameter("type", type)
                .setParameter("sign", SignGenerator.getSign())
                .setParameter("language", languageUsed.toString())
                .setParameter("timeOffSet", timeOffSetUsed)
                .build();
        HttpGet httpGet = new HttpGet(uri);
        httpGet.setConfig(requestConfig);
        String srtResult = null;
        int StatusCode = 404;
        HttpResponse httpResponse = httpCilent.execute(httpGet);
        StatusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
            JSONObject jsonObject = JSONObject.parseObject(srtResult);
            if ("true".equalsIgnoreCase(jsonObject.get("success").toString())) {
                return JSONObject.toJSONString(jsonObject.get("result"));
            } else {
                throw new Exception("cannot extract data," + jsonObject.get("errDes"));
            }
        } else {
            srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
            throw new Exception("cannot extract data," + srtResult);
        }
    }

}
